package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
	"timed_tasks/utils"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Static("/scripts", "scripts")
	r.Static("/logs", "logs")
	r.POST("/scripts/*path", func(ctx *gin.Context) {
		path := ctx.Request.URL.Path
		filePath := strings.TrimPrefix(path, "/")
		stat, err := os.Stat(filePath)
		if os.IsNotExist(err) {
			ctx.AbortWithStatus(404)
			return
		}
		if stat.IsDir() {
			ctx.JSON(400, gin.H{"msg": "目录并不是可执行文件!!!"})
			return
		}
		s := strings.Split(filePath, "/")
		dir := strings.Join(s[:len(s)-1], "/")
		fileName := s[len(s)-1]
		var cmd string
		switch s[1] {
		case "go":
			cmd = fmt.Sprintf("cd %s && chmod 777 ./%s && ./%s", dir, fileName, fileName)
			break
		case "python":
			cmd = fmt.Sprintf("cd %s && python %s", dir, fileName)
			break

		case "shell":
			cmd = fmt.Sprintf("cd %s && sh %s", dir, fileName)
			break
		default:
			ctx.JSON(400, gin.H{"msg": "请求路径错误!!!"})
			return
		}
		dateTime := time.Now().Format(time.DateTime)
		dateTime = strings.ReplaceAll(dateTime, ":", "_")
		dateTime = strings.ReplaceAll(dateTime, " ", "___")
		dateTime = strings.ReplaceAll(dateTime, "-", "_")
		logDirs := []string{"logs", strings.Join(s, "_")}
		logDir := filepath.Join(logDirs...)
		// 创建当前脚本，当前时间的文件夹
		_ = os.MkdirAll(filepath.Join(logDir), os.ModePerm)
		// 删除一个月以前的日志文件
		scriptsLogsPath := filepath.Join(logDirs...)
		utils.DeletePreMouthFile(scriptsLogsPath)

		// 日志文件位置
		logStdoutFilePath := filepath.Join(logDir, fmt.Sprintf("%s___stdout.log", dateTime))
		logStderrFilePath := filepath.Join(logDir, fmt.Sprintf("%s___stderr.log", dateTime))
		// 创建两个日志文件，用来记录系统错误和系统输出
		logStdout, _ := os.Create(logStdoutFilePath)
		logStderr, _ := os.Create(logStderrFilePath)
		defer func() {
			_ = logStdout.Close()
			_ = logStderr.Close()
		}()
		// 构建命令
		command := exec.Command("bash", "-c", cmd)
		command.Stdout = logStdout
		command.Stderr = logStderr
		// 运行
		err = command.Run()
		if err != nil {
			ctx.JSON(500, gin.H{"msg": "错误", "err": err.Error(), "cmd": cmd})
			return
		}
		ctx.JSON(200, gin.H{"msg": "运行成功!", "cmd": cmd, "stdout_log": logStdoutFilePath, "stderr_log": logStderrFilePath})
		return
	})
	// 注册路由
	r.Run(":11000")
}
